package net.documentshare.docu.corpus;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.documentshare.docu.DocuBean;
import net.documentshare.docu.DocuUtils;
import net.documentshare.impl.AbstractAttention;
import net.documentshare.utils.ItSiteUtil;
import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.SQLValue;
import net.simpleframework.content.EContentType;
import net.simpleframework.core.ado.IDataObjectQuery;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.page.PageRequestResponse;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.ui.tabs.EMatchMethod;
import net.simpleframework.web.page.component.ui.tabs.TabHref;
import net.simpleframework.web.page.component.ui.tabs.TabsUtils;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

public class CorpusUtils {
	public static String getApplicationUrl(final Object o, final Object t) {
		final StringBuffer buf = new StringBuffer();
		buf.append("/docu_corpus/").append(o).append("-").append(t).append(".html");
		return buf.toString();
	}

	public static String tabs(PageRequestResponse requestResponse) {
		final List<TabHref> tabHrefs = new ArrayList<TabHref>();
		TabHref href = new TabHref("全部", getApplicationUrl(0, 0));
		href.setMatchMethod(EMatchMethod.startsWith);
		tabHrefs.add(href);
		if (ItSiteUtil.isManage(requestResponse, DocuUtils.applicationModule)) {
			href = new TabHref("文辑管理", getApplicationUrl(1, 0));
			href.setMatchMethod(EMatchMethod.startsWith);
			tabHrefs.add(href);
		}
		return TabsUtils.tabs(requestResponse, tabHrefs.toArray(new TabHref[tabHrefs.size()]));
	}

	public static String getApplicationUrl(PageRequestResponse requestResponse) {
		return "/docu_corpus.html";
	}

	public static List<Map<String, String>> queryBycorpusId(CorpusBean docuBean, int view) {
		String sql = "SELECT t.docId,t1.fileName,t1.path1,t1.path2 FROM it_docu_corpusofdoc t,it_docu_documentshare t1 where t.CorpusId='"
				+ docuBean.getId().getValue() + "' and t.docId=t1.id limit " + view;
		JdbcTemplate temp = new JdbcTemplate(DocuUtils.applicationModule.getDataObjectManager().getDataSource());
		final List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
		temp.query(sql, new ResultSetExtractor<Object>() {
			@Override
			public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
				while (rs.next()) {
					final Map<String, String> data = new HashMap<String, String>();
					String docId = rs.getString(1);
					String fileName = rs.getString(2);
					String path1 = rs.getString(3);
					String path2 = rs.getString(4);
					int pageCount = DocuUtils.pageCount(path2, path1, docId);
					data.put("docId", docId);
					data.put("fileName", fileName);
					data.put("pageCount", String.valueOf(pageCount));
					dataList.add(data);
				}
				return null;
			}

		});
		return dataList;
	}

	public static String getMyCorposDocViewUrl(String corposId) {
		return "/docu_corpus/v/" + corposId + ".html";
	}

	public static String wrapOpenLink(final CorpusBean corpusBean) {
		final StringBuffer buf = new StringBuffer();
		if (corpusBean != null) {
			buf.append("<a target=\"_blank\"");
			buf.append(" href=\"" + getMyCorposDocViewUrl(corpusBean.getId().getValue().toString()) + "?userId=" + corpusBean.getUserId() + "\"");
			buf.append(">").append(corpusBean.getName()).append("</a>");
		}
		return buf.toString();
	}

	public static String getCorpusFrontImage(CorpusBean corpusBean, PageRequestResponse requestResponse) {
		String fontImage = requestResponse.getContextPath() + "/simple/docu/corpus/image/Unregistered.jpg";
		if (corpusBean.getFrontCover() != null && Long.parseLong(corpusBean.getFrontCover().getValue().toString()) != 0) {
			fontImage = DocuUtils.getPageImgSrc(requestResponse, DocuUtils.applicationModule.getBean(DocuBean.class, corpusBean.getFrontCover()));
		}
		return fontImage;
	}

	public static long getCount() {
		return DocuUtils.applicationModule.getDataObjectManager().getCount(new SQLValue("select count(id) from it_docu_Corpus"));
	}

	public static AbstractAttention getAttention(Object userId, Object id) {
		final ITableEntityManager tMgr = DocuUtils.applicationModule.getDataObjectManager(CorpusAttention.class);
		return tMgr.queryForObject(new ExpressionValue("userId=? and corpusId=?", new Object[] { userId, id }), CorpusAttention.class);
	}

	public static IDataObjectQuery<?> queryCorpus(PageRequestResponse compParameter) {
		String type = compParameter.getRequestParameter("type");
		StringBuffer exp = new StringBuffer("1=1");
		final List<Object> param = new ArrayList<Object>();
		if (!StringUtils.hasText(type)) {
			type = "newest";
		}
		if (type.equals("related")) {
			String corpusId = compParameter.getRequestParameter("corpusId");
			CorpusBean bean = DocuUtils.applicationModule.getBean(CorpusBean.class, Long.parseLong(corpusId));
			return DocuUtils.applicationModule.createCorpusLuceneManager(new ComponentParameter(compParameter.request, compParameter.response, null))
					.getLuceneQuery(bean.getName());

		}
		if (type.equals("recommend") && exp.length() == 0) {
			param.add(EContentType.recommended);
			exp.append("contentType =?");
		} else if (type.equals("recommend")) {
			param.add(EContentType.recommended);
			exp.append(" and contentType =? ");
		}
		if (type.equals("newest")) {
			exp.append(" order by createDate desc");
		}
		if (type.equals("viewest")) {
			exp.append(" order by readTime desc");
		}
		return DocuUtils.applicationModule.queryBean(exp.toString(), param.toArray(), CorpusBean.class);
	}

	public static CorpusBean addViews(String id) {
		synchronized (DocuUtils.applicationModule) {
			CorpusBean bean = (CorpusBean) DocuUtils.applicationModule.getBean(CorpusBean.class, id);
			bean.setReadTime(bean.getReadTime() + 1);
			DocuUtils.applicationModule.doUpdate(new Object[] { "readTime" }, bean);
			return bean;
		}
	}
}
